package common;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class CorpusProcessorNoisy {

	public static int run(HashMap<String, Integer> tCount, HashMap<String, HashMap<String, Integer>> ttCount, HashMap<String, HashMap<String, Integer>> wtCount, HashMap<String,String> mostFrequentSubsequentPOS) {
		
		int tTotalCount = 0;
		
		try {
			File file = new File("CoNLL2009-ST-English-train-pos.txt");
			String prevPOS = "<s>";
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line = null;

			while ((line = br.readLine()) != null) {                                                                                                                                                       
				if (line.isEmpty()) {
					prevPOS = "<s>";
					if (tCount.containsKey("<s>")){
						tCount.put("<s>", tCount.get("<s>") + 1);
					} else {
						tCount.put("<s>", 1);
					}
					continue;
				}
				String[] cols = line.split("\t");

				// POS tag count
				if (!tCount.containsKey(cols[4])) {
					tCount.put(cols[4], 1);
				} else {
					tCount.put(cols[4], tCount.get(cols[4]) + 1);
				}
				tTotalCount++;

				// Word-POS pairs + count
				if (!wtCount.containsKey(cols[2])) {
					HashMap<String, Integer> h = new HashMap<String, Integer>();
					h.put(cols[4], 1);
					wtCount.put(cols[2], h);
				} else {
					if (wtCount.get(cols[2]).containsKey(cols[4])) {
						wtCount.get(cols[2]).put(cols[4],
								wtCount.get(cols[2]).get(cols[4]) + 1);

					} else {
						wtCount.get(cols[2]).put(cols[4], 1);
					}
				}

				// POS bigram pairs count
				if (!ttCount.containsKey(prevPOS)) {
					HashMap<String, Integer> h = new HashMap<String, Integer>();
					h.put(cols[4], 1);
					ttCount.put(prevPOS, h);
				} else {
					if (ttCount.get(prevPOS).containsKey(cols[4])) {
						ttCount.get(prevPOS).put(cols[4],
								ttCount.get(prevPOS).get(cols[4]) + 1);
					} else {
						ttCount.get(prevPOS).put(cols[4], 1);
					}
				}
				
				prevPOS = cols[4];
				
			}
			
			// fill most frequent subsequent POS tags
			ArrayList<String> prevPOStag = new ArrayList<String>(ttCount.keySet());
			ArrayList<String> currPOStag = new ArrayList<String>();
			for (String pos : prevPOStag){
				int tempMax = 0;
				String tempPOS = "";
				currPOStag = new ArrayList<String>(ttCount.get(pos).keySet());
				for (String subPos : currPOStag){
					// innan i condition: Character.isLetter(subPos.charAt(0)) && 
					if (ttCount.get(pos).get(subPos)>tempMax){
						tempMax=ttCount.get(pos).get(subPos);
						tempPOS=subPos;
					}
				}
				mostFrequentSubsequentPOS.put(pos, tempPOS);
			}
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return tTotalCount;

	}

}
